<template>
  <div class="bgff p20" v-loading="loading">
    <el-form :inline="true" :model="formInline" class="demo-form-inline mb20">
      <el-form-item label="网关名">
        <el-select v-model="gatewayId" placeholder="请选择">
          <el-option v-for="item in gatewaylist" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="time"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="serch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-download" @click="outPdf">导出PDF</el-button>
      </el-form-item>
    </el-form>
    <div class="con" id="week-report">
      <div>
        <h3 class="titles mb20">概况总览</h3>
        <div class="bor">
          <div
            class="p1"
          >{{gatewayNameFn(gatewayId)}} 最近7天（{{timeText}}）用电安全检测情况： {{all.eq_total}}个（报警：{{all.eq_alarm}}，离线：{{all.eq_offline}}，正常：{{all.eq_online>0?all.eq_online:0}}）。</div>
          <table
            cellpadding="0"
            cellspacing="1"
            width="100%"
            class="eqmt-con bb"
            style="background-color: white;"
          >
            <tr class="tr1">
              <td>监控区域名称</td>
              <td>剩余电流</td>
              <td>线缆电流</td>
              <td>线缆温度</td>
              <td>线缆电压</td>
              <td>离线记录</td>
            </tr>
            <tr v-for="item in tableData" :key="item.id">
              <td>{{item.name}}</td>
              <td
                v-for="(it,index) in [item.list_a_counts,item.a_counts,item.t_counts,item.u_counts]"
                :key="index"
              >
                <!-- <img
                  v-if="item.status==1"
                  class="img-tips"
                  src=""
                />
                <img
                  v-else-if="item.status==0"
                  class="img-tips"
                  src=""
                />-->
                <em>
                  <img
                    v-if="it===null"
                    class="img-tips"
                    src=""
                  />
                  <img
                    v-else-if="it>0"
                    class="img-tips"
                    src=""
                  />
                  <img
                    v-else
                    class="img-tips"
                    src=""
                  />
                </em>
              </td>
              <td>{{item.is_offline?"有":"无"}}</td>
            </tr>
            <tr class="fz12 tx-r">
              <td colspan="6">
                注：
                <img
                  class="img-tips"
                  src=""
                />为报警，
                <img
                  class="img-tips"
                  src=""
                />为正常，
                <img
                  class="img-tips"
                  src=""
                />为离线
              </td>
            </tr>
          </table>
          <p
            class="fz12 p10"
          >报警次数总计{{all.total()}}次。剩余电流报警{{all.di}}次，线缆电流报警{{all.a}}次，线缆温度报警为{{all.t}}次，线缆电压报警为{{all.v}}次。详情请登录安心电管家管理平台。</p>
        </div>
      </div>
      <div>
        <h3 class="titles mt20">特征分析</h3>
        <div v-for="item in tableData" :key="item.id">
          <h3 class="mt20 p10 tx-c tz-bg">{{item.name}}</h3>
          <div class="clear">
            <div
              :id="`line_a_h_${item.id}`"
              class="bor fl"
              style="width:48%;height:200px;margin-top:20px;"
            ></div>
            <div
              :id="`line_list_a_h_${item.id}`"
              class="bor fr"
              style="width:48%;height:200px;margin-top:20px;"
            ></div>
            <div
              :id="`line_u_h_${item.id}`"
              class="bor fl"
              style="width:48%;height:200px;margin-top:20px;"
            ></div>
            <div
              :id="`line_t_h_${item.id}`"
              class="bor fr"
              style="width:48%;height:200px;margin-top:20px;"
            ></div>
          </div>
        </div>
      </div>
      <div class="mt20">
        <h3 class="titles mb10">危害分类</h3>
        <div v-html="article"></div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  _chartReportWeekNew,
  _gatewaysAllGet,
  _articleShow
} from "@/http/ajax";
import htmlToPdf from "@/utils/htmlToPdf";
import conf from "@/http/uploadconfig";
export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          let _now = Date.now(),
            seven = 7 * 24 * 60 * 60 * 1000,
            sevenDays = _now - seven;
          return time.getTime() > _now; //大于今天的禁止
        }
      },
      time: new Date(),
      timeText: "",
      gatewayId: "",
      gatewaylist: [{}],
      loading: true,
      formInline: {
        input: ""
      },
      tableData: [],
      all: {
        a: 0,
        di: 0,
        t: 0,
        v: 0,
        total: () => {
          return this.all.a + this.all.di + this.all.t + this.all.v;
        },
        eq_total: 0,
        eq_alarm: 0,
        eq_offline: 0,
        eq_online: 0
      },
      article: ""
    };
  },
  created() {
    this.getGatewaysAll();
  },
  methods: {
    gatewayNameFn(v) {
      let text = "";
      this.gatewaylist.forEach(el => {
        if (v == el.id) {
          text = el.name;
        }
      });
      return text;
    },
    // pdf 导出
    outPdf() {
      htmlToPdf.downloadPDF(
        document.querySelector("#week-report"),
        this.gatewayNameFn(this.gatewayId) +"（" + this.timeText + "）周报"
      );
    },
    // 搜索
    serch() {
      this.getData();
    },

    getData() {
      if(!this.time){
          this.$message({
              message: "部门不能为空",
              type: "warning"
            });
        return
      }
      let data = {
        endTime: new Date(this.time).format("yyyy-MM-dd"),
        gatewayId: this.gatewayId,
        type: "pc",
        startTime: new Date(
          new Date(this.time).setDate(new Date(this.time).getDate() - 7)
        ).format("yyyy-MM-dd")
        // startTime: "2019-07-01"
      };
      this.loading = true;
      this.timeText = data.startTime + "~" + data.endTime;
      _chartReportWeekNew(
        data,
        res => {
          this.tableData = res.equipments;
          this.tableData.forEach(el => {
            setTimeout(() => {
              // 画图
              this.doRes(el.id, "a_h", el.counts);
              this.doRes(el.id, "list_a_h", el.counts);
              this.doRes(el.id, "u_h", el.counts);
              this.doRes(el.id, "t_h", el.counts);
            }, 100);
          });
          this.all.eq_total = res.total_numbers;
          this.all.eq_alarm = res.alarm_numbers;
          this.all.eq_offline = res.offline_numbers;
          this.all.eq_online =
            this.all.eq_total - this.all.eq_alarm - this.all.eq_offline;
          this.loading = false;
          console.log(res)
          this.getArticle();
        },
        err => {}
      );
    },
    // 获取所有网关
    getGatewaysAll() {
      let user = JSON.parse(sessionStorage.user);
      let data = {
        deptId: user.deptId || user.dept.id || "",
        level: sessionStorage.level
      };
      _gatewaysAllGet(
        data,
        res => {
          this.gatewaylist = res;
          if (this.gatewaylist.length) {
            this.gatewayId = this.gatewaylist[0].id;
          } else {
            this.gatewayId = '';
          }
          this.getData();
        },
        err => {}
      );
    },
    doRes(id, type, res) {
      let data = [];
      this.all.di = 0;
      this.all.a = 0;
      this.all.t = 0;
      this.all.v = 0;
      if (res && res.length) {
        res.forEach(el => {
          // 拼接数据
          this.all.di += el.a_di;
          this.all.a += el.a_i;
          this.all.t += el.a_t;
          this.all.v += el.a_v;
          if(el[type]){
            data = data.concat(JSON.parse(el[type]));
          }
        });
      }
      let hasdata = false; // 判断是否有数据
      for (let i = 0; i < data.length; i++) {
        if (data[i]) {
          hasdata = true;
          break;
        }
      }
      if (hasdata) {
        console.log(data)
        this.drawLine(id, type, data);
      } else {
        this.noDdata(id, type);
      }
    },
    // 画图
    drawLine(id, type, res) {
      let datas = [],
        type_modul = {
          a_h: "高峰用电电流（A）",
          list_a_h: "线缆最高温度（℃）",
          u_h: "高峰剩余电流（mA）",
          t_h: "监控区域最高温度（℃）"
        };
      res.forEach(el => {
        // if(id===4){
        // console.log(type,new Date(el.create_time).format("yyyy-MM-dd hh:mm:ss"),el[type])
        // }
        datas.push({
          name: new Date(el.create_time),
          value: [
            new Date(el.create_time).format("yyyy-MM-dd hh:mm:ss"),
            (type=='a_h'?el[type]/10:el[type])
          ]
        });
      });
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(
        document.getElementById(`line_${type}_${id}`)
      );
      let option = {
        title: {
          left: 20,
          top: 10,
          text: type_modul[type]
        },
        tooltip: {
          trigger: "axis",
          formatter: function(params) {
            params = params[0];
            return `<div >
              <p>时间：${new Date(params.name).format(
                "yyyy-MM-dd hh:mm:ss"
              )}</p> 
              <p style="border-top:1px solid #fff;">数据：${
                params.value[1]
              }</p> 
             </div>`;
          },
          axisPointer: {
            animation: false
          }
        },
        xAxis: {
          type: "time",
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          splitLine: {
            show: false
          }
        },
        series: [
          {
            name: type_modul[type],
            type: "line",
            showSymbol: false,
            hoverAnimation: false,
            data: datas
          }
        ]
      };
      setTimeout(() => {
        myChart.setOption(option);
      }, 200);
    },
    // 没有数据
    noDdata(id, type) {
      let type_modul = {
        a_h: "高峰用电电流",
        list_a_h: "线缆最高温度",
        u_h: "高峰剩余电流",
        t_h: "监控区域最高温度"
      };
      $(`#line_${type}_${id}`).css({ height: "240px" })
        .html(`<div class="bold pl30 pt10">
            ${type_modul[type]}
          </div>
          <div class="tx-c">
            <img alt="" style="height: 200px" src="${conf.nodata1}"> 
          </div>`);
    },
    // 获取知识库
    getArticle() {
      _articleShow(
        5,
        res => {
          this.article = res.content;
        },
        err => {}
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.con {
  min-width: 860px;
  .bor {
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  .tz-bg {
    background: #a0d468;
    color: #fff;
  }
  .titles {
    height: 37px;
    line-height: 37px;
    font-size: 14px;
    border: 1px solid #d2d2d2;
    border-left: 3px solid #509de2;
    padding-left: 10px;
    padding-right: 26px;
    background: #fff;
    color: #666;
    display: inline-block;
  }
  .p1 {
    background: #509de3;
    border-radius: 3px;
    height: 50px;
    line-height: 50px;
    color: #fff;
    font-size: 14px;
    padding-left: 20px;
    text-align: left;
  }
  .eqmt-con {
    background: #f0f0f0;
    text-align: left;
    border-collapse: inherit;
    border-spacing: 2px;
    tr td {
      background: #f6f6f6;
      padding: 10px 20px;
    }
    .tr1 td {
      background: #f7f7f7;
      border-top: 1px solid #bfbfbf;
      border-bottom: 3px solid #a0d468;
    }
    .img-tips {
      width: 9px;
      height: 9px;
      vertical-align: middle;
    }
  }
}
</style>
